const UserModel = require('../../model/user_model.js');
const BaseAdminService = require('./base_admin_service.js');
const cloudBase = require('../../../../framework/cloud/cloud_base.js');

class UserMgrService extends BaseAdminService {

    // 列表
    async list({
        keyword,
        page,
        size
    }) {
        let where = {};
        if (keyword) {
            where['or'] = [
                {
                    'user_nickname': {
                        '$regex': keyword,
                        '$options': 'like'
                    }
                },
                {
                    'user_phone': {
                        '$regex': keyword,
                        '$options': 'like'
                    }
                },
            ];
        }
        let orderBy = { 'ID': 'desc' };
        let isTotal = true;
        let data = await UserModel.getList(where, '*', orderBy, page, size, isTotal);
        return data;
    }

    // 保存
    async save({
        _id,
        user_nickname,
        user_phone,
        user_is_admin
    }) {
        let oldInfo = await UserModel.getOne({ 'user_phone': user_phone });
        if (oldInfo && oldInfo._id != _id) {
            this.AppError('手机号已存在');
        }
        if (_id) {
            let info = await UserModel.getOne({ '_id': _id });
            if (!info) {
                this.AppError('司机信息不存在');
            }
        }
        // 入库
        let data = {
            user_nickname,
            user_phone,
            user_is_admin
        };
        if (_id) {
            // 更新
            await UserModel.edit({ '_id': _id }, data);
        } else {
            // 新增
            await UserModel.insert(data);
        }
        return {
            res: true
        };
    }

}

module.exports = UserMgrService;